package cn.app.android.sichuanxiaoke.com.xiaokeapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.app.android.sichuanxiaoke.com.xiaokeapp.R;
import cn.app.android.sichuanxiaoke.com.xiaokeapp.utils.ConstantUtils;
import cn.app.android.sichuanxiaoke.com.xiaokeapp.utils.OtherUtils;

public class UserRegisterActivity extends AppCompatActivity {
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.loginCode)
    EditText loginCode;
    @BindView(R.id.phone_error)
    TextView phone_error;
    @BindView(R.id.get_phone_code)
    Button phoneCode;
    @BindView(R.id.userpassword)
    EditText password;
    @BindView(R.id.passwordIsOK)
    EditText passwordagain;
    @BindView(R.id.tb)
    Toolbar tb;

    private int NumTag=60; //倒计时标记

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_register);
        ButterKnife.bind(this);
        initUI();
        BindEvent();

    }
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            if(what == 0){
                phoneCode.setText(NumTag+"s");
            }else if(what == 1) {
                phoneCode.setText(getResources().getString(R.string.get_SMS_code));
                phoneCode.setEnabled(true);
            }
        }
    };

    private void BindEvent() {
        setSupportActionBar(tb);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        tb.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                phone_error.setText("");

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(TextUtils.isEmpty(s)){
                    phone.setHint(getResources().getString(R.string.your_phone_is_null));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                boolean phoneNumber = OtherUtils.validatePhoneNumber(String.valueOf(s));
                if(!phoneNumber){
                    phone.setHint(getResources().getString(R.string.please_enter_istrue));

                }
            }
        });
        loginCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(TextUtils.isEmpty(s)){
                    loginCode.setHint(getResources().getString(R.string.please_enter_code));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initUI() {

    }
    @OnClick({R.id.UserRegister,R.id.get_phone_code})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.get_phone_code:
                GetUserLoginCode();
                break;
            case R.id.UserRegister:
                UserRegister();
                break;

        }



    }

    private void GetUserLoginCode() {
        Refresh();
        final String mphone = phone.getText().toString();
        boolean phoneNumber = OtherUtils.validatePhoneNumber(mphone);


        if(!phoneNumber){
            phone_error.setText(getResources().getString(R.string.please_enter_istrue));
            return;
        }
        //String format = String.format(ConstantUtils.USER_REGISTER_CODE_URL, mphone);
        HttpParams params = new HttpParams();
        params.put("phone",mphone);
        params.put("type","reg");
        OkGo.<String>post(ConstantUtils.USER_REGISTER_CODE_URL).params(params).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                Log.i("USER_REGISTER_URL","onSuccess--"+body);
                try {
                    JSONObject object = new JSONObject(body);
                    String status = object.optString("status");
                    if (status.equals(getResources().getString(R.string.is_success))){
                        String message="验证码已发送到手机"+mphone+",请注意查收";
                        Toast.makeText(UserRegisterActivity.this,message,Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                String body = response.body();
                Log.i("USER_REGISTER_URL","onError--"+body);
            }
        });



    }

    private void UserRegister() {
        String mphone = phone.getText().toString();
        String mloginCode = loginCode.getText().toString();
        String mpassword = password.getText().toString();
        String mpasswordagain = passwordagain.getText().toString();
        if(mpassword.isEmpty() || mpasswordagain.isEmpty()){
            password.setError("密码不能为空");
            return;
        }
        if(!mpassword.equals(mpasswordagain)){
            Toast.makeText(this,"两次输入的密码不一致",Toast.LENGTH_SHORT).show();
            return;
        }
        //String format = String.format(ConstantUtils.USER_REGISTER_URL, mphone,mloginCode,mpassword,mpasswordagain);
        //Log.i("UserRegister","接口--------"+format);

        HttpParams params = new HttpParams();
        params.put("username",mphone);
        params.put("verify_code",mloginCode);
        params.put("password",mpassword);
        params.put("password2",mpasswordagain);
        OkGo.<String>post(ConstantUtils.USER_REGISTER_URL).params(params).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                Log.i("UserRegister","onSuccess--"+body);
                try {
                    JSONObject object = new JSONObject(body);
                    int status = object.optInt("status");
                    if(status == 1){
                        startActivity(new Intent(UserRegisterActivity.this,UserRegisterSuccessActivity.class));
                        finish();
                        return;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Toast.makeText(UserRegisterActivity.this,"注册失败，请查看电话是否已注册",Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onError(Response<String> response) {
                String body = response.body();
                Log.i("UserRegister","onError--"+body);


            }
        });

        /*Intent intent=new Intent(this, PayActivity.class);
        startActivity(intent);*/

    }

    private void Refresh(){
        phoneCode.setEnabled(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 60; i++) {
                    NumTag--;
                    try {
                        handler.sendEmptyMessage(0);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                NumTag=60;
                handler.sendEmptyMessage(1);

            }
        }).start();
    }
}
